package com.hnu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hnu.common.Constants;
import com.hnu.dto.Result;
import com.hnu.entity.Admin;
import com.hnu.service.AdminService;
import com.hnu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @Author hj
 * @Date 2023/12/20 8:49
 * @PackageName:com.hnu.controller
 * @ClassName: AdminController
 * @Description: create a class
 * @Version 1.0
 */
@CrossOrigin //服务器端解决跨域
@RequestMapping("/admin")
@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;

    //注册功能
    @PostMapping("/regs")
    public Result regs(@RequestBody Admin admin) {
        //对密码进行加密
        admin.setAdminPassword(SecurityUtils.md5Hex(admin.getAdminPassword()));
        //设置创建时间
        admin.setAdminCreateTime(new Date());
        admin.setAdminUpdateTime(new Date());
        //调用服务层方法做添加操作
        boolean flang = adminService.save(admin);
        if (flang) {
            return Result.ok(Constants.ADD_SUCCESS).data(flang);
        }
        return Result.error(Constants.ADD_ERROR);
    }

    //登录功能
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin, HttpSession session) {
        //对象密码进行加密处理
        String pass = SecurityUtils.md5Hex(admin.getAdminPassword());
        //根据用户名查询用户信息
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getAdminName, admin.getAdminName());
        //使用adminService调用方法查询
        Admin admin1 = adminService.getOne(qw);
        if (admin1 == null) {
            //帐号不存在
            return Result.error(Constants.LOGIN_UNKNOW_USERNAME);
        }
        if (!admin1.getAdminPassword().equals(pass)) {
            //密码错误
            return Result.error(Constants.LOGIN_ERROR_PASSWORD);
        }
        session.setAttribute("admin", admin1);
        return Result.ok(Constants.LOGIN_OK).data(admin1);
    }

    //管理员列表

    /**
     * 分页查询所有管理员
     * @param pageNum
     * @param pageSize
     * @return Result
     */
    @PostMapping("/findAll/{pageNum}/{pageSize}")
    public Result findAll(@PathVariable int pageNum,
                          @PathVariable int pageSize)  {
        Page<Admin> page = adminService.page(new Page<>(pageNum, pageSize));
        return Result.ok(Constants.OK).data(page);
    }

}
